<template>
  <div>
    <div v-if="!accountUpdateDialogVisible"  class="mod-config" id="mod-config-id">
      <div v-if="isAuth('ent:user:paging')" class="div-s" id="div-s-id" >
        <el-form :model="params" :label-position="labelPosition" ref="queryFormRef" :inline="true" label-width="70px" class="queryFormed">
          <el-row class="row-s">
            <el-col class="col-center" :span="6">
              <el-form-item label="账号" prop="name">
                <el-input v-model="params.name" placeholder="请输入账号" @clear="clearName" clearable ></el-input>
              </el-form-item>
            </el-col>
            <el-col class="col-center" :span="6">
              <el-form-item label="姓名" prop="nickName">
                <el-input v-model="params.nickName" placeholder="请输入姓名" @clear="clearNickName" clearable ></el-input>
              </el-form-item>
            </el-col>
              <el-col class="col-center" :span="6">
                <el-form-item label="角色" prop="roleName">
                  <el-input v-model="params.roleName" placeholder="请输入角色名称" @clear="clearRoleName" clearable ></el-input>
                </el-form-item>
              </el-col>

            <el-col class="col-right" :span="6" :offset="0">
              <el-form-item class="item-all">
                <el-button class="buttonItem" size="mini" plain @click="clickReset()">重 置</el-button>
                <el-button class="buttonItem" size="mini" type="primary" @click="clickSearch()">搜 索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="div-e" id="div-e-id">
        <div class="div-inquire" id="div-inquire-id">
          <div class="in-t">
            <div class="in-ts"></div>
            <h3 >账户管理</h3>
          </div>
<!--          <div v-if="!inqerts" class="div-button">
            <el-button v-if="isAuth('ent:user:delete')" size="mini" type="danger" icon="el-icon-delete" @click="clickDeleteBatch" :disabled="this.tableSelection.length < 1">批量删除</el-button>
          </div>-->
        </div>
        <el-table
          ref="multipleTable"
          :data="tableData"
          :max-height="table.tableHeight"
          :header-cell-style="{background:'#F5F7FA'}"
          style="width: 100%"
          v-loading="dataListLoading"
          @selection-change="handleSelectionChange"
          fit>
<!--          <el-table-column
            type="selection"
            width="55">
          </el-table-column>-->
          <el-table-column
            label="角色名称"
            width="200"
            prop="roleName"
            align="center">

          </el-table-column>
          <el-table-column
            prop="name"
            label="账号"
            width="200"
            align="center">
          </el-table-column>
          <el-table-column
            prop="nickName"
            label="姓名"
            width="200"
            align="center">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
            width="200"
            align="center">
          </el-table-column>
          <el-table-column
            prop="statusStr"
            label="状态"
            align="center">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.updateAbleFlag === 1 && isAuth('ent:user:update')" type="text" size="mini" class="btn-text-normal" @click="showAccountUpdateDialog(scope.row)">修改</el-button>
              <el-button v-if="isAuth('ent:user:resetPassword')" type="text" size="mini" class="btn-text-normal" @click="clickResetPassWord(scope.row)">重置密码</el-button>
              <el-button v-if="scope.row.updateAbleFlag === 1 && isAuth('ent:user:delete')" type="text" size="mini" class="btn-text-danger" @click="clickDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="changePageSize"
          @current-change="turnToPage"
          :current-page="queryInfo.pageIndex"
          :page-sizes="[5, 10, 20, 50, 100, 200]"
          :page-size="queryInfo.pageSize "
          layout="total, prev, pager, next, sizes, jumper"
          :total="totalPage"
          id="div-e-paging-id">
        </el-pagination>
      </div>
    </div>
    <authorization-form v-if="accountUpdateDialogVisible">
      <template slot="head">
        <div class="div-s" >
          <el-form :model="accountForm" :rules="accountFormRules"  ref="accountFormRefs" label-width="100px">
            <el-row>
              <el-col :span="11">
                <el-form-item label="账号" prop="name">
                  <el-input v-model="accountForm.name" placeholder="" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11" :offset="1">
                <el-form-item label="姓名" prop="nickName">
                  <el-input v-model="accountForm.nickName" placeholder="" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="accountForm.mobile" placeholder="" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" >
                <el-form-item label="角色" prop="roleId">
                  <el-select v-model="accountForm.roleId" @change="changeRoleOption" clearable>
                    <el-option v-for="item in roleList"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="账号标记颜色">
                  <el-select v-model="accountForm.colorCode" placeholder="请选择">
                    <el-option
                      v-for="item in colorOption"
                      :key="item.name"
                      :label="item.name"
                      :value="item.code">
                      <div style="display: flex;justify-content: space-between;align-items: center;padding: 0px 5px">
                        <div style="display: inline-block">{{item.name}}</div>
                        <div :style="`background-color: ${item.value};`" style="display: inline-block;border-radius: 50%;width:18px;height:18px"></div>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="accountForm.status">
                    <el-radio :label="1">可用</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template slot=left><function-authorization ref="funcAuthRefs"  :isUpdatable="false" :default-checked-menu-id-list="accountForm.menuIdList"></function-authorization></template>
      <template slot=right><data-authorization ref="dataAuthRefs" :isUpdatable="false"   :default-checked-id-list="accountForm.deptIdList"></data-authorization></template>
      <template slot=bottom>
        <div style="display: flex;justify-content: center">
          <el-button @click="accountUpdateDialogVisible = false">返 回</el-button>
          <el-button type="primary" @click="clickUpdate">保 存</el-button>
        </div>
      </template>
    </authorization-form>
<!--    <el-dialog
      title="账户修改"
      :visible.sync="accountUpdateDialogVisible"
      width="60%"
      >
      <div>
        <el-form :model="accountForm" :rules="accountFormRules"  ref="accountFormRefs" label-width="100px">
          <el-form-item label="账号" prop="name">
            <el-input v-model="accountForm.name" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="nickName">
            <el-input v-model="accountForm.nickName" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="accountForm.mobile" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select v-model="accountForm.roleId" clearable>
              <el-option v-for="item in roleList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="accountForm.status">
              <el-radio :label="1">可用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="accountUpdateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickUpdate">确 定</el-button>
      </span>
    </el-dialog>-->
    <el-dialog
      title="提示"
      :visible.sync="resetPassWordDialogVisible"
      width="30%">
      <div>
        <i class="el-icon-info" style="color: #FAAD14; font-size: 21px"></i>
        <span>密码重置后新密码为手机号后六位，确认要重置 <span style="color:  #6E92E9">"1234567910"</span> 账号</span>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="resetPassWordDialogVisible = false" >取 消</el-button>
    <el-button type="primary" @click="resetPassWordDialogVisible = false">确 认</el-button>
  </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <div>
        <i class="el-icon-info" style="color: #FAAD14; font-size: 21px"></i>
        <span>确认要删除账号 <span style="color:  #6E92E9">"1234567910"</span> 吗？</span>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="deleteDialogVisible = false" >取 消</el-button>
    <el-button type="primary" @click="deleteDialogVisible = false">确 认</el-button>
  </span>
    </el-dialog>
    <el-dialog
      title=""
      :visible.sync="deleteFailDialogVisible"
      width="40%">
      <span slot="title" style="font-size: 18px;">提示</span>
      <div style="display: flex">
        <i class="el-icon-warning" style="color: #E6A23C;font-size: 30px;margin-right: 10px"></i>
        <div style="font-size: 16px;line-height: 30px;width: 100%">
          <span style="display: block">该账号无法删除，具体原因如下：</span>
          <span style="display: block">企业成交量：{{deleteForm.dealEnterpriseAmount}}个</span>
          <span style="display: block">个人成交量：{{deleteForm.dealCustomerAmount}}个</span>
          <span style="display: block">意向客户：{{deleteForm.intentionAmount}}个</span>
          <el-row >
            <el-col :span="3">区域销售：</el-col>
          <el-col :span="21">
            <el-row>
              <el-col v-for="(sale, index) in deleteForm.saleAreaList" :span="12" >{{`${sale.cityName || ""} ${sale.areaName || ""} ${sale.saleName || ""};`}}</el-col>
            </el-row>
          </el-col>
        </el-row>
          <el-row >
            <el-col :span="3">区域管理：</el-col>
            <el-col :span="21">
              <el-col v-for="(area, index) in deleteForm.mangerAreaList"  :span="12">{{`${area.cityName || ""} ${area.name || ""};`}}</el-col>
            </el-col>
          </el-row>

        </div>
      </div>

      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="deleteFailDialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>

</template>

<script>
import BasePaging from '../../common/BasePaging'
import {isAuth} from '../../../utils'
import {getRoleList, getRoleById} from '../../../api/customer/role'
import {resetPwd, deleteAccount, updateAccount, verifyDeleteAccount} from '../../../api/customer/account'
import AuthorizationForm from './Component/AuthorizationForm'
import FunctionAuthorization from './Component/FunctionAuthorization'
import DataAuthorization from './Component/DataAuthorization'
import {accountColorList} from '../../../api/customer/commom'
export default {
  name: 'account',
  components: {DataAuthorization, FunctionAuthorization, AuthorizationForm},
  extends: BasePaging,
  data () {
    return {
      // 测试状态
      testFalse: false,
      colorOption: accountColorList,
      // table选中列表
      tableSelection: [],
      bodyHeight: 0,
      searchHeight: 0,
      inqerts: false,
      params: {
        name: ''
      },
      accountForm: {
        'id': '',
        'roleId': '',
        'nickName': '',
        'roleName': '',
        'name': '',
        'mobile': '',
        'status': 0,
        'menuIdList': [],
        'deptIdList': [],
        'colorCode': 'deepBlue'
      },
      // 表单验证规则
      accountFormRules: {
        name: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      },
      // 角色列表
      roleList: [],
      labelPosition: 'right',
      accountUpdateDialogVisible: false,
      resetPassWordDialogVisible: false,
      deleteFailDialogVisible: false,
      dataListLoading: false,
      tableData: [],
      deleteForm: {
        dealEnterpriseAmount: null,
        dealCustomerAmount: null,
        intentionAmount: null,
        saleAreaList: [],
        mangerAreaList: []
      }
    }
  },
  created () {
    if (isAuth('ent:user:paging')) {
      this.paging()
    }
  },
  methods: {
    isAuth (auth) {
      return isAuth(auth)
    },
    // 获取分页
    paging () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/ent/user/paging'),
        method: 'post',
        data: this.$http.adornData({
          'conditions': {
            'name': this.params.name,
            'nickName': this.params.nickName,
            'roleName': this.params.roleName,
            'mobile': '',
            'roleId': ''
          },
          'inOrder': '',
          'orderBy': '',
          'pageNum': this.queryInfo.pageIndex,
          'pageSize': this.queryInfo.pageSize
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          data.data.records.forEach((item) => { item.statusStr = item.status ? '可用' : '禁用' })
          this.tableData = data.data.records
          // console.log('tableData', this.tableData)
          this.totalPage = data.data.total
        } else {
          this.$message.error(data.msg)
        }
        this.dataListLoading = false
      })
    },
    // 获取角色列表
    getRoleList () {
      getRoleList((data) => { this.roleList = data.data })
    },
    // 点击搜索
    clickSearch () {
      this.accountForm.name = this.params.name
      this.queryInfo.pageIndex = 1
      this.paging()
    },
    clearNickName () {
      this.clickSearch()
    },
    clearRoleName () {
      this.clickSearch()
    },
    // 清空角色姓名input
    clearName () {
      this.queryInfo.pageIndex = 1
      this.paging()
    },

    // 点击重置
    clickReset () {
      this.$refs['queryFormRef'].resetFields()
      this.paging()
    },

    // 展示账户修改对话框
    showAccountUpdateDialog (account) {
      this.getRoleList()
      this.accountUpdateDialogVisible = true
      this.accountForm.id = account.id
      this.accountForm.name = account.name
      this.accountForm.nickName = account.nickName
      this.accountForm.mobile = account.mobile
      this.accountForm.roleId = account.roleId
      this.accountForm.status = account.status
      this.accountForm.colorCode = account.colorCode
      this.setRoleAuth(account.roleId)
    },

    // 点击修改账户
    clickUpdate () {
      updateAccount({
        'id': this.accountForm.id,
        'roleId': this.accountForm.roleId,
        'nickName': this.accountForm.nickName,
        'name': this.accountForm.name,
        'mobile': this.accountForm.mobile,
        'status': this.accountForm.status,
        'colorCode': this.accountForm.colorCode
      },
        () => {
          this.accountUpdateDialogVisible = false
          this.$message.success('修改成功!')
          this.paging()
        })
    },
    // 展示重置密码对话框
    showResetPassWordDialog (account) {
      this.$confirm(`密码重置后新密码为手机号后六位，确认要重置 ${account.name} 的密码吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPwd(account.id,
          () => {
            this.$message.success('重置密码成功')
            this.paging()
          })
      })
    },
    // 重置密码
    clickResetPassWord (account) {
      this.showResetPassWordDialog(account)
    },
    // 过滤table选择的id
    getTableSelectionIdList (selectionList = []) {
      return selectionList.map((item) => item.id)
    },
    // Table操作
    handleSelectionChange (selection) {
      // console.log('selection', selection)
      this.tableSelection = selection
    },
    // 显示删除确认对话框
    showDeleteDialog (account) {
      this.$confirm(`确认要删除账号 ${account.mobile} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        verifyDeleteAccount(account.id, ({data}) => {
          const {deleteAble, userDataCountList} = data
          if (deleteAble) {
            deleteAccount(account.id, () => {
              this.paging()
            })
          } else {
            if (userDataCountList) {
              Object.keys(this.deleteForm).forEach((key) => {
                this.deleteForm[`${key}`] = userDataCountList[0][`${key}`]
              })
              this.deleteFailDialogVisible = true
            }
          }
        })
/*        deleteAccount(account.id, (data) => {
          this.paging()
        }, ({data}) => {
          if (data[0]) {
            this.deleteFailDialogVisible = true
            Object.keys(this.deleteForm).forEach((key) => {
              this.deleteForm[`${key}`] = data[0][`${key}`]
            })
          }
        }) */
      })
    },
    // 显示批量删除对话框
    showDeleteDialogBatch () {
      let selectIdList = this.getTableSelectionIdList(this.tableSelection)
      this.$confirm(`确认要批量删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAccount(selectIdList, () => { this.paging() })
      })
    },
    // 点击删除账号
    clickDelete (account) {
      this.showDeleteDialog(account)
    },
    // 批量删除
    clickDeleteBatch () {
      this.showDeleteDialogBatch()
    },
    changeRoleOption (roleId) {
      getRoleById(roleId,
        ({data}) => {
          this.accountForm.menuIdList = data.menuIdList
          this.accountForm.deptIdList = data.deptIdList
        })
    },
    setRoleAuth (roleId) {
      this.changeRoleOption(roleId)
    }
  }
}
</script>
